using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MeshTool
{
    public static bool GetPos(List<Plane> mPlanes, Vector3 origin, Vector3 dest, Ray edgeRay, Vector2 u0, Vector2 u1, out Vector3 pos, out Vector2 uv)
    {
        pos = Vector3.zero;
        uv = Vector2.zero;
        float cur_min_dist = 0;
        
        for (int k = 0; k < mPlanes.Count; k++)
        {
            var plane = mPlanes[k];
            edgeRay.origin = origin;
            edgeRay.direction = (dest - origin).normalized;
            float dist;
            float maxDist = Vector3.Distance(origin, dest);
            if (cur_min_dist == 0)
            {
                cur_min_dist = maxDist;
            }

            if (!plane.Raycast(edgeRay, out dist))
            {
                continue;
            }
            if (dist >= maxDist)
            {
                continue;
            }
            else
            {
                if (dist < cur_min_dist)
                {
                    cur_min_dist = dist;
                    pos = edgeRay.GetPoint(dist);
                    var relativeDist = dist / maxDist;
                    // Compute new uv by doing Linear interpolation between uv1 and uv2
                    uv.x = Mathf.Lerp(u0.x, u1.x, relativeDist);
                    uv.y = Mathf.Lerp(u0.y, u1.y, relativeDist);
                    //return true;
                }
            }
        }

        //if (cur_min_dist > 0)
        //{
        //    return true;
        //}
        return false;
    }
}
